import os
from PyPDF2 import PdfReader, PdfWriter

input_dir = "待合并PDF文档"
output = PdfWriter()
for file in os.listdir("待合并PDF文档"):
    print("合并文件：", file)
    file_path = os.path.join(input_dir, file)
    input = PdfReader(open(file_path, "rb"))
    pageCount = len(input.pages)
    for iPage in range(pageCount):
        output.add_page(input.pages[iPage])

with open("合并的python文档.pdf", "wb") as outputfile:
    # 注意这里的写法和正常的上下文文件写入是相反的
    output.write(outputfile)
